package web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.Cart;
import bean.CartItem;
import dao.ComputerDAO;
import dao.impl.ComputerDAOJdbcImpl;
import entity.Computer;

public class ShoppingServlet extends HttpServlet {

		public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			request.setCharacterEncoding("utf-8");
			String uri = request.getRequestURI();
			String path = uri.substring(uri.lastIndexOf("/"),
					uri.lastIndexOf("."));
			if(path.equals("/list")){
				ComputerDAO dao = new ComputerDAOJdbcImpl();
				try {
					List<Computer> computers = 
						dao.findAll();
					request.setAttribute("computers", computers);
					request.getRequestDispatcher("computer_list.jsp")
					.forward(request, response);
				} catch (Exception e) {
					e.printStackTrace();
					throw new ServletException(e);
				}
			}else if(path.equals("/buy")){
				long id = Long.parseLong(request.getParameter("id"));
				ComputerDAO dao = new ComputerDAOJdbcImpl();
				try {
					Computer c = dao.findById(id);
					CartItem item = new CartItem();
					item.setComputer(c);
					item.setQty(1);
					HttpSession session = request.getSession();
					Cart cart = (Cart) session.getAttribute("cart");
					if(cart == null){
						cart = new Cart();
						session.setAttribute("cart", cart);
					}
					boolean flag = cart.add(item);
					if(!flag){
						request.setAttribute("buy_err" + id, "已经购买过该商品");
						request.getRequestDispatcher("list.do")
						.forward(request, response);
					}else{
						response.sendRedirect("list.do");
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw new ServletException(e);
				}
				
			}else if(path.equals("/delete")){
				System.out.println("delete");
				long id = Long.parseLong(request.getParameter("id"));
				HttpSession session = request.getSession();
				Cart cart = (Cart) session.getAttribute("cart");
				cart.delete(id);
				response.sendRedirect("cart.jsp");
			}else if(path.equals("/update")){
				long id = Long.parseLong(request.getParameter("id"));
				int qty = Integer.parseInt(request.getParameter("qty"));
				HttpSession session = request.getSession();
				Cart cart = (Cart) session.getAttribute("cart");
				cart.modify(id, qty);
				response.sendRedirect("cart.jsp");
			}else if(path.equals("/clear")){
				HttpSession session = request.getSession();
				Cart cart = (Cart) session.getAttribute("cart");
				cart.clear();
				response.sendRedirect("cart.jsp");
			}
	
	}

}
